package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        // 判断内容是否大于140字
        if (dto == null || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        User user = UserThreadLocalUtil.get();
        if(user==null||user.getUserId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApComment apComment = new ApComment();
//        apComment.setId(); //mongo可以自动赋值
        if(user.getUserId()==0){ //以游客身份评论
            apComment.setUserId(user.getUserId());
            apComment.setUserName("游客");
            apComment.setImage(null);
        }else{
            ResponseResult<ApUser> responseResult = userFeign.getUserById(user.getUserId());
            ApUser apUser = responseResult.getData();
            apComment.setUserId(user.getUserId());
            apComment.setUserName(apUser.getName());
            apComment.setImage(apUser.getImage());
        }

        apComment.setArticleId(dto.getArticleId());
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setRepay(0);
        apComment.setCreatedTime(new Date());
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult load(CommentDto dto) {
        // 根据文章id查询评论列表
        // 按照创建时间倒序排列
        // 分页判断数据小于前端传递的最小时间
        // 每页默认显示10条评论数据
        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() >= 50) {
            dto.setSize(10);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        // 分页 和 排序
        query.limit(dto.getSize());
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);

        // TODO 登录用户需要查看当前返回的列表中是否已经有点赞记录
        User user = UserThreadLocalUtil.get();
        if(user!=null&&user.getUserId()!=0){
            List<ApCommentVo> commentVoList = new ArrayList<>();
            for (ApComment comment : apComments) {
                ApCommentVo commentVo = new ApCommentVo();
                BeanUtils.copyProperties(comment,commentVo);
                Boolean hasKey = redisTemplate.hasKey("comment_like_" + user.getUserId() + "_" + comment.getId());
                commentVo.setOperation(hasKey?0:1); //0代表当前登录人对这个评论点赞
                commentVoList.add(commentVo);
            }
            return ResponseResult.okResult(commentVoList);
        }

        return ResponseResult.okResult(apComments);
    }

    private StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        // 获取当前的用户
        User user = UserThreadLocalUtil.get();
        if (user == null||user.getUserId()==0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构建点赞记录
        ApCommentLike like = new ApCommentLike();
        like.setUserId(user.getUserId());
        like.setCommentId(dto.getCommentId());
        like.setOperation(dto.getOperation());

        // 保存点赞或取消点赞记录
        mongoTemplate.save(like);

        // 更新评论表的点赞数量+1或者-1
        Query commentQuery = new Query();
        commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
        Update update = new Update();
        if (dto.getOperation() == 1) {
            update.inc("likes",-1);
            redisTemplate.delete("comment_like_"+user.getUserId()+"_"+dto.getCommentId());

        }else{
            update.inc("likes",1);
            redisTemplate.boundValueOps("comment_like_"+user.getUserId()+"_"+dto.getCommentId()).set("");
        }
        mongoTemplate.updateFirst(commentQuery, update, ApComment.class);

        return ResponseResult.okResult();
    }

}
